 //
//  MLDOAuthViewController.swift
//  Sina
//
//  Created by 万世豪情 on 15/10/21.
//  Copyright © 2015年 万世豪情. All rights reserved.
//

import UIKit
import AFNetworking

class MLDOAuthViewController: UIViewController, UIWebViewDelegate {

    let APP_ID = "1236660626"
    
    let APP_SECRET = "d627d0fba0f7f0ecace41a6d3e9f8d88"
    let REDIRECT_URL = "http://www.douyutv.com/"
    
    var webView = UIWebView?()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        
        //webView的用户登录界面
        let webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        webView.delegate = self
        
       let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_ID)&redirect_uri=\(REDIRECT_URL)"
        printLog(urlString)
        //初始化url
        let url = NSURL(string: urlString)
        //初始化请求
        let request = NSURLRequest(URL:url!)
        
        webView.loadRequest(request)
       
        view.addSubview(webView)
        
        self.webView = webView
    }

    func setupNav() {
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoinput")
        
        }
//    @objc private func autoinput(){
//        let script = "document.getElementById('userId').value='fengwu1059@vip.qq.com';document.getElementById('passwd').value='molunda.'"
//        self.webView?.stringByEvaluatingJavaScriptFromString(script)
    @objc private func autoinput(){
        let script = "document.getElementById('userId').value='15210006687';document.getElementById('passwd').value='wangbo159753'"
        self.webView?.stringByEvaluatingJavaScriptFromString(script)

    
        
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        
        if urlString!.hasPrefix(REDIRECT_URL) {
        
            let codePre = "code="
            
            let range = (urlString! as NSString).rangeOfString(codePre)
            
            if range.location != NSNotFound {
            
                let code = (urlString! as NSString).substringFromIndex(range.location + range.length)
                printLog("code=\(code)")
                loadAccessToken(code)
                return false

            }
        }
        return true
    }
    
    private func loadAccessToken(code: NSString){
    
    
        let manager = AFHTTPSessionManager()
        //给默认的序列化器添加一个可以接受的内容类型????
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let usrString = "https://api.weibo.com/oauth2/access_token"
        //参数
        let params = [
            "client_id": APP_ID,
            "client_secret": APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": REDIRECT_URL
        ]
        
        manager.POST(usrString, parameters: params, success: { (datatask, result) -> Void in
             printLog("请=͟͟͞͞求=͟͟͞͞成=͟͟͞͞功fuck=͟͟͞͞:请⃠求⃠成⃠功⃠\(result)")
            
            //字典转成模型
            if let res = (result as? [String: AnyObject]) {
                
                let account = MLDUserAccount(dictionary: res)
                
                //保存
                printLog(account)
            }
            }) { (datatask, error) -> Void in
                printLog("请求失败:\(error)")

        }
        
    }
    
    
    
    
    
    
    
    
    
    

}
